<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import MenuApi from '/@/api/sys/menu.class';
  import { getNodes, nodesToCascader } from '/@/utils/helper/customHelper';
  import { listToTree } from '/@/utils/helper/treeHelper';
  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const menuApi = new MenuApi();
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        const treeData = listToTree(await menuApi.list(), { pid: 'parentId' });
        treeData.unshift({ id: 0, icon: '', type: 0, title: '顶级菜单' });
        const nodes = getNodes();
        updateSchema([
          {
            field: 'parentId',
            componentProps: { treeData },
          },
          {
            field: 'nodes',
            componentProps: {
              options: nodesToCascader(nodes),
            },
          },
        ]);

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          console.log('values', values);
          // console.log('premission', MenuApi.nodes);
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          if (isUpdate.value == true) {
            await menuApi.update(values);
          } else {
            await menuApi.create(values);
          }
          // console.log('premission', MenuApi.nodes);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
